<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Controllers\Api\Third\SdDdzyApiController;

class SdDdzyController extends Controller
{
    //映射额定电压和分类
    public function mapVolClass()
    {
        if(request()->isMethod('post')){
            $id = request('id',0);
            $table = 'sd_ddzy_voltage_class_map';
            if ($id) { //修改
                $val = request('vol_class');
                $res = DB::table($table)->where('id',$id)->update(['vol_class'=>$val]);
                return $res ? 1 : 0;
            }
            //添加
            $params = request()->only('val','type');
            if ($exists = DB::table($table)->where('val',$params['val'])->exists()) {
                return '数据已存在！';
            }
            $params['vol_class'] = $params['type'] === 0 ? request('voltage','') : request('class','');
            $res = DB::table($table)->insert($params);
            return $res ? 1 : 0;
        }
    }

    //样品类型展示
    public function index(Request $request)
    {
        $data = [];
        //山东带电作业对照表信息
        $data['sdTools'] = DB::table('sd_ddzy_tool_map')->get();
        $data['sdTestitem'] = DB::table('sd_ddzy_testitem_map')->orderBy('ddzy_id','asc')->get();
        $data['sdStdNums'] = DB::table('sd_ddzy_standard_map')->get();
        $data['sdVolClass'] = DB::table('sd_ddzy_voltage_class_map')->get();
        //本系统基础表信息
        $data['tools'] = DB::table('a_tool')->where('ishide',0)->pluck('name');
        $data['testitem'] = DB::table('a_testitem')->pluck('name');
        $data['stdNums'] = DB::table('a_standard')->pluck('num');
        $volClass = DB::table('a_voltage_class')->select('type','val')->get();
        $voltage = $class = [];
        foreach ($volClass as $item) {
            if ($item->type == 0) {
                $voltage[] = $item->val;
            }else{
                $class[] = $item->val;
            }
        }
        $data['volClass'] = [
            0=>array_unique($voltage),
            1=>array_unique($class),
        ];
        //返回
        return view('admin.sdDdzy.index',compact('data'));
    }

    //删除
    public function del(Request $request){
        $params = $request->only('type','id');
        switch ($params['type']) {
            case 'tool':
                $table = 'sd_ddzy_tool_map';
                break;
            case 'testitem':
                $table = 'sd_ddzy_testitem_map';
                break;
            case 'std':
                $table = 'sd_ddzy_standard_map';
                break;
            default:
                $table = '';
                break;
        }
        $res = $table ? DB::table($table)->delete($params['id']) : 0;
        return $res ? 1 : 0;
    }

    //映射检测标准
    public function mapStd()
    {
        if(request()->isMethod('post')){ //编辑：添加、修改
            $id = request('id',0);
            if ($id) { //编辑
                $std_num = request('std_num');
                $res = DB::table('sd_ddzy_standard_map')->where('id',$id)->update(['std_num'=>$std_num]);
                return $res ? 1 : 0;
            }
            $params = request()->only('num','std_num');
            if ($exists = DB::table('sd_ddzy_standard_map')->where('num',$params['num'])->exists()) {
                return '数据已存在！';
            }
            $res = DB::table('sd_ddzy_standard_map')->insert($params);
            return $res ? 1 : 0;
        }
    }

    //映射工器具类型
    public function mapTool()
    {
        if(request()->isMethod('post')){ //编辑：添加、修改
            $id = request('id',0);
            if ($id) { //编辑
                $tool_name = request('tool_name');
                $res = DB::table('sd_ddzy_tool_map')->where('id',$id)->update(['tool_name'=>$tool_name]);
                return $res ? 1 : 0;
            }
            $params = request()->only('name','tool_name');
            $valid = validator()->make($params,[
                'name'=>'required|max:30',
                'tool_name'=> 'required|max:30',
            ]);
            if ($valid->fails()) {
                return $valid->errors()->first();
            }
            if ($exists = DB::table('sd_ddzy_tool_map')->where('name',$params['name'])->exists()) {
                return '数据已存在！';
            }
            $res = DB::table('sd_ddzy_tool_map')->insert($params);
            return $res ? 1 : 0;
        }
    }

    //映射检测项目
    public function mapTestitem()
    {
        if(request()->isMethod('post')){
            $id = request('id');
            if ($id) {
                $params = request()->only('id','testitem_name');
                $res = DB::table('sd_ddzy_testitem_map')->where('id',$params['id'])->update(['testitem_name'=>implode(',', $params['testitem_name'])]);
                return $res ? 1 : 0;
            }
            $params = request()->only('name','testitem_name','ddzy_id');
            if (DB::table('sd_ddzy_testitem_map')->where('name',$params['name'])->orWhere('ddzy_id',$params['ddzy_id'])->exists()) {
                return '数据已存在！';
            }
            $res = DB::table('sd_ddzy_testitem_map')->insert($params);
            return $res ? 1 : 0;
        }
        $data = [];
        $data['testitem'] = DB::table('a_testitem')->pluck('name');
        $data['sdTestitem'] = DB::table('sd_ddzy_testitem_map')->orderBy('ddzy_id','asc')->get();;
        $SdDdzyApiController = new SdDdzyApiController();
        $data['Sditems'] = $SdDdzyApiController->getTestItems();
        // dd($data);
        return view('admin.sdDdzy.mapTestitem',compact('data'));
    }

    //自动添加工器具类型或检测项目
    public function autoAdd()
    {
        $type = request('type','');
        $sdDdzyApiCon = new SdDdzyApiController();
        switch($type){
            case 'tool':
                $data = $sdDdzyApiCon->getTools(1);
                $table = 'sd_ddzy_tool_map';
                break;
            case 'testitem':
                $data = $sdDdzyApiCon->getTestitems();
                $table = 'sd_ddzy_testitem_map';
                break;
            default:
                $data = null;
                $table = '';
        }
        if (is_null($data) || !$table) {
            return '请求失败！';
        }
        // dd($data);
        $old_tools = DB::table($table)->pluck('name')->toArray();
        $new_tools = [];
        // dd($data);
        $can = 0;
        foreach ($data as $k=>$item) {
            $item = (array)$item;
            if (!in_array($item['name'], $old_tools)) {
                $can += 1;
                $in = ['name'=>$item['name']];
                if($type == 'testitem'){
                    $in['ddzy_id'] = $k;
                }
                $new_tools[] = $in;
            }
        }
        if($can === 0){
            return '未找到可以添加的数据，请手动添加！'; //可能是工器具类型，也可能是检测项目，所以不能肯定对照的是什么
        }
        $res = 1;
        if ($new_tools) {
            $res = DB::table($table)->insert($new_tools);
        }
        return $res == count($new_tools) ? 1 :0;
    }

    //工器具类型-对照项目中的试验数据
    public function mapItemKey(){
        $id = request('id');
        if(request()->isMethod('post')){
            $key_data = request('keyData');
            foreach ($key_data as $key_id => $item) {
                $key_mean = explode('-',$item['key']);
                $up = [
                    'testdata_key_id'=>$key_id,
                    'key'=>$key_mean[0],
                    'mean'=>isset($key_mean[1]) ? $key_mean[1] : '',
                    'pro_type_id'=>isset($key_mean[2]) ? $key_mean[2] : '',
                    'bei'=>$item['bei'],
                ];
                if(DB::table('sd_ddzy_testdata_key_map')->where('testdata_key_id',$key_id)->exists()){
                    unset($up['testdata_key_id']);
                    $res = DB::table('sd_ddzy_testdata_key_map')->where('testdata_key_id',$key_id)->update($up);
                }else{
                    $res = DB::table('sd_ddzy_testdata_key_map')->insert($up);
                }
            }
            return $res ? 1 : 0;
        }
        $data = [];
        $sd_tool = DB::table('sd_ddzy_tool_map')->find($id);
        $items = DB::table('a_std_tool_item_rel as a')
                    ->leftJoin('a_standard as b','a.std_id','=','b.id')
                    ->leftJoin('a_tool as c','a.tool_id','=','c.id')
                    ->leftJoin('a_testitem as d','a.testitem_id','=','d.id')
                    ->leftJoin('sd_ddzy_tool_map as e','c.name','=','e.tool_name')
                    ->where('e.name',$sd_tool->name)
                    ->select('e.tool_name','b.num as std_num','d.name as item_name','a.id as std_tool_item_rel_id')
                    ->orderBy('a.sort','asc')
                    ->get();
        $items2 = [];
        foreach ($items as $item) {
            $item->keys = DB::table('a_testdata_key')->where('std_tool_item_rel_id',$item->std_tool_item_rel_id)->select('id','data_key','data_unit')->orderBy('sort','asc')->get();
            $items2[$item->tool_name][$item->std_num][] = $item;
            $items2[$item->tool_name]['rows'] = isset($items2[$item->tool_name]['rows']) ? ($items2[$item->tool_name]['rows'] + 1) : 1;
        }
        // dd($items2);
        $data['items'] = $items2;
        $SdDdzyApiController = new SdDdzyApiController();
        $data['Sditems'] = $SdDdzyApiController->getTestItems();
        $data['SditemKeys'] = DB::table('sd_ddzy_testdata_key_map')->get()->keyBy('testdata_key_id')->toArray();
        $SditemMaps = DB::table('sd_ddzy_testitem_map')->get();
        $itemMaps = [];
        foreach ($SditemMaps as $SditemMap) {
            $testitem_names = explode(',',$SditemMap->testitem_name);
            foreach($testitem_names as $testitem_name){
                $itemMaps[$testitem_name][] = $SditemMap->name;
            }
        }
        $data['itemMaps'] = $itemMaps;
        return view('admin.sdDdzy.mapItemKey',compact('data'));
    }
}
